local storyboard = require( "storyboard" )
local scene = storyboard.newScene()

function scene:updateLevelCallback()
return function(delta)
   self.gameWorld:update(delta)
   self:updateHUD(delta)
end
end

function scene:createGameObjects()
   self.gameWorld = GameWorld:new()
   self.hud       = display.newGroup()

   self.view:insert(self.gameWorld)
   self.view:insert(self.hud)
   self:createHUD()

   -- sound
   local saw = audio.loadStream(Sound.get('saw'))
   audio.play(saw)

   timer.performWithDelay(
      500,
      function(event)
         self:pushGas(halfX,halfY)
      end,
      -1
   )
end

function scene:createHUD()
   self.hud.timeText = display.newText({text='0:00',textFont=12,parent=self.hud,x=X*0.09,y=Y*0.95})

   local iceButtonStartX,iceButtonStartY = X*0.9,Y*0.1
   local iceButton = display.newImage(self.hud,'resources/sprites/icon_ice.png')
   iceButton.height,iceButton.width = X*0.05,X*0.05
   iceButton.x,iceButton.y = iceButtonStartX,iceButtonStartY

   iceButton:addEventListener('touch',function(event)
      if iceButton.timeout > 0 then return false end

      if event.phase == 'began' then
         logger:debug('ini')
         display.getCurrentStage():setFocus(iceButton)
         iceButton.focus = true
      end

      if iceButton.focus ~= true then return false end

      if event.phase == 'moved' then
         iceButton.x,iceButton.y = event.x,event.y
      elseif event.phase == 'ended' then
         logger:debug('end')
            iceButton.x,iceButton.y = iceButtonStartX,iceButtonStartY
            iceButton.timeout = ICE_TIMEOUT
            scene:pushSnowFlake(event.x,event.y)
         display.getCurrentStage():setFocus(nil)
         iceButton.focus = false
      end
      return true
   end)

   local whirlwindButtonStartX,whirlwindButtonStartY = X*0.8,Y*0.1
   local whirlwindButton = display.newImage(self.hud,'resources/sprites/whirlwind.png')
   whirlwindButton.height,whirlwindButton.width = X*0.05,X*0.05
   whirlwindButton.x,whirlwindButton.y = whirlwindButtonStartX,whirlwindButtonStartY

   whirlwindButton:addEventListener('touch',function(event)
      if whirlwindButton.timeout > 0 then return false end

      if event.phase == 'began' then
         logger:debug('ini')
         display.getCurrentStage():setFocus(whirlwindButton)
         whirlwindButton.focus = true
      end

      if whirlwindButton.focus ~= true then return false end

      if event.phase == 'moved' then
         whirlwindButton.x,whirlwindButton.y = event.x,event.y
      elseif event.phase == 'ended' then
         logger:debug('end')
            whirlwindButton.x,whirlwindButton.y = whirlwindButtonStartX,whirlwindButtonStartY
            whirlwindButton.timeout = WHIRLWIND_TIMEOUT
            scene:pushWhirlwind(event.x,event.y)
         display.getCurrentStage():setFocus(nil)
         whirlwindButton.focus = false
      end
      return true
   end)

   local lightningButtonStartX,lightningButtonStartY = X*0.7,Y*0.1
   local lightningButton = display.newImage(self.hud,'resources/sprites/icon_lightning.png')
   lightningButton.height,lightningButton.width = X*0.05,X*0.05
   lightningButton.x,lightningButton.y = lightningButtonStartX,lightningButtonStartY
   lightningButton:addEventListener('touch',function(event)
      if lightningButton.timeout > 0 then return false end

      if event.phase == 'began' then
         display.getCurrentStage():setFocus(lightningButton)
         lightningButton.focus = true
      end

      if lightningButton.focus ~= true then return false end

      if event.phase == 'moved' then
         lightningButton.x,lightningButton.y = event.x,event.y
      elseif event.phase == 'ended' then
            lightningButton.x,lightningButton.y = lightningButtonStartX,lightningButtonStartY
            lightningButton.timeout = LIGHTNING_TIMEOUT
            scene:pushThunderbolt(event.x,event.y)
         display.getCurrentStage():setFocus(nil)
         lightningButton.focus = false
      end
      return true
   end)

   self.hud.iceButton = iceButton
      self.hud.iceButton.timeout = ICE_TIMEOUT
      self.hud.iceButton.alpha = 0
   self.hud.whirlwindButton = whirlwindButton
      self.hud.whirlwindButton.timeout = WHIRLWIND_TIMEOUT
      self.hud.whirlwindButton.alpha = 0
   self.hud.lightningButton = lightningButton
      self.hud.lightningButton.timeout = LIGHTNING_TIMEOUT
      self.hud.lightningButton.alpha = 0
end

function scene:pushGas(x,y)
   local gas = display.newImage(self.gameWorld,'resources/sprites/gas_effect.png')
   gas:scale(0.01,0.01)
   gas.x,gas.y = x,y
   gas:setFillColor(1,0,0,1)

   transition.to(
      gas,
      {
         time=2000,
         alpha=0.0,
         xScale=0.10,
         yScale=0.10,
         onComplete = function()
            DisplayObjectUtils.safeRemove(gas)
         end
      }
   )
end

function scene:pushWhirlwind(x,y)
   local whirlwindSprite = display.newImage(self.view,'resources/sprites/whirlwind.png')
   whirlwindSprite.alpha = 0.4
   whirlwindSprite:scale(0.4,0.4)
   whirlwindSprite.x,whirlwindSprite.y = x,y - whirlwindSprite.contentHeight * 0.4

   local whirlwindTimer = timer.performWithDelay(
      60,
      function()
         whirlwindSprite:scale(-1,1)
      end,
      math.floor((WHIRLWIND_IN_AIR_TIMEOUT * 1000) / (60 + 10))
   )

   transition.to(
      whirlwindSprite,
      {
         time=WHIRLWIND_IN_AIR_TIMEOUT * 1000,
         onComplete = function()
            timer.cancel(whirlwindTimer)
            DisplayObjectUtils.safeRemove(whirlwindSprite)
         end
      }
   )
end

function scene:pushSnowFlake(x,y)
   local snowFlakeSprite = display.newImage(self.view,'resources/sprites/snow_flake.png')
   snowFlakeSprite:scale(0.1,0.1)
   snowFlakeSprite.x,snowFlakeSprite.y = x,y

   local blankScreen = display.newRect(self.view,halfX,halfY,X,Y)
   blankScreen:setFillColor(0.6,0.6,1,0.7)
   transition.to(
      blankScreen,
      {
         time=600,
         alpha=0,
         onComplete=function()
            DisplayObjectUtils.safeRemove(blankScreen)
         end
      }
   )

   transition.to(
      snowFlakeSprite,
      {
         time=500,
         xScale=2.0,
         yScale=2.0,
         alpha =0.0,
         onComplete = function()
            DisplayObjectUtils.safeRemove(snowFlakeSprite)
         end
      }
   )
end

function scene:pushThunderbolt(x,y)
   local thunderSprite = display.newImage(self.view,'resources/sprites/bolt.png')
   thunderSprite:scale(0.2,0.2)
   thunderSprite.x,thunderSprite.y = x,y - thunderSprite.contentHeight * 0.25

   local blankScreen = display.newRect(self.view,halfX,halfY,X,Y)
   blankScreen:setFillColor(1,1,1,0.7)
   transition.to(
      blankScreen,
      {
         time=300,
         alpha=0,
         onComplete=function()
            DisplayObjectUtils.safeRemove(blankScreen)
         end
      }
   )

   transition.to(
      thunderSprite,
      {
         time=600,
         alpha=0,
         onComplete=function()
            DisplayObjectUtils.safeRemove(thunderSprite)
         end
      }
   )
end

function scene:updateHUD(delta)
   local allSeconds = math.floor(self.gameWorld.time)

   self.hud.iceButton.timeout = self.hud.iceButton.timeout - delta
   self.hud.whirlwindButton.timeout = self.hud.whirlwindButton.timeout - delta
   self.hud.lightningButton.timeout = self.hud.lightningButton.timeout - delta

   self.hud.iceButton.alpha = 1.0 - math.max(0,self.hud.iceButton.timeout) / ICE_TIMEOUT
   self.hud.whirlwindButton.alpha = 1.0 - math.max(0,self.hud.whirlwindButton.timeout) / WHIRLWIND_TIMEOUT
   self.hud.lightningButton.alpha = 1.0 - math.max(0,self.hud.lightningButton.timeout) / ICE_TIMEOUT

   local minutes = math.floor(allSeconds / 60)
   local seconds = allSeconds % 60

   self.hud.timeText.text = string.format('%d:%02d',minutes,seconds)
end

--Methods
function scene:createScene(event)
   logger:gameEvent("Create Gameplay Scene")
   storyboard.removeAll()
   self.timers = {}

   scene:createGameObjects()
end
function scene:enterScene(event)
   logger:gameEvent("Enter Gameplay Scene")

   GameController.getInstance().addCallback(scene:updateLevelCallback(), 'mainLoop')
   GameController.getInstance():beginGame()
end

function scene:exitScene(event)
   logger:gameEvent("exit Gameplay Scene")

   GameController.getInstance().clearAllCallbacks()
   GameController.getInstance():stop()
end

function scene:destroyScene(event)
   logger:gameEvent("destroy Gameplay Scene")

   for i=#self.timers,1,-1 do
      timer.cancel(self.timers[i])
      table.remove(self.timers,i)
   end

   GameController.getInstance().clearAllCallbacks()
   GameController.getInstance():stop()
end

scene:addEventListener("createScene",scene)
scene:addEventListener("enterScene",scene)
scene:addEventListener("exitScene",scene)
scene:addEventListener("destroyScene", scene)

return scene